package com.panshi.service.impl;

import com.panshi.mapper.IUserMapper;
import com.panshi.pojo.User;
import com.panshi.service.IUserService;
import com.panshi.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    IUserMapper iUserMapper;

    @Autowired
    RedisUtil redisUtil;


    @Override
    public List<User> getUserArr() {
        return iUserMapper.getUserArr();
    }

    @Override
    public User getUserId(Integer id) {
        return iUserMapper.getUserId(id);
    }

    @Override
    public Integer getUser(String username, String password) {
//        從reids中拿取用戶
        Set<Object> objects = redisUtil.sGet("user_" + username);
        if (objects.isEmpty()) {
            for (Object o : objects) {
                User u = (User) o;
                if (password.equals(u.getUsername())) {
                    //如果redis賬戶 密碼存在返迴 true
                    System.out.println("redis存在返迴true" + u);
                    return u.getUid();
                }
            }
        }
        User user = iUserMapper.getUser(username, password);
//        數據庫數據庫不為null
        if (user != null) {
            System.out.println("mysql存在存在返迴true" + user);
            //            更新redis
            redisUtil.sSet("user_" + username, user);
            return user.getUid();
        }
//        redis  數據庫都不存在 返迴false
        return null;
    }
}
